﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService.TransportHandle
// 文 件 名：	ReceiveBlock
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/6/18 20:38:26
//========================================
using Common;
using SFJDService.EventHandle;
using System;

namespace SFJDService.TransportHandle
{
    /// <summary>
    /// 缓存的字节块  为何不能用值类型（结构体）， 只能用引用类型？？
    /// </summary>
    public class ReceiveBlock
    {
        public const int MaxCount = 100;
        const int MaxLength = PacketFileTransport.FileByteCount * MaxCount;
        public int FileIndex { set; get; }
        public int IndexStart { set; get; }
        public int IndexEnd { set; get; }
        int IndexCount { set; get; }
        public int Length { set; get; }
        public byte[] Bytes { set; get; }

        /// <summary>
        /// 字节块
        /// </summary>
        /// <param name="packet"></param>
        internal ReceiveBlock(ClassTransportInfo transportInfo, PacketFileTransport packet)
        {
            IndexStart = (packet.ByteIndex / (MaxCount)) * MaxCount;
            IndexEnd = IndexStart + MaxCount - 1;
            IndexCount = 1;
            FileIndex = packet.FileIndex;
            Length = packet.Length;
            Bytes = new byte[MaxLength];
            Buffer.BlockCopy(packet.Bytes, 0, Bytes, 0, packet.Length);
            if(packet.ByteIndexTotal == 1)
            {
                var data = new SSTransReceiveBlockFullData() { TransInfo = transportInfo, Block = this };
                EventBus.instance.Trigger(data); //把字节块存入文件
            }
        }

        /// <summary>
        /// 将字节添加入字节块中
        /// </summary>
        /// <param name="packet"></param>
        /// <returns>1:字节块已完成; 0:字节已储存在块中; -1:字节不在此块范围内; </returns>
        internal int AddPacket(ClassTransportInfo transportInfo, PacketFileTransport packet)
        {
            if(FileIndex == packet.FileIndex && packet.ByteIndex >= IndexStart & packet.ByteIndex <= IndexEnd)
            {
                try
                {
                    Buffer.BlockCopy(packet.Bytes, 0, Bytes, PacketFileTransport.FileByteCount * (packet.ByteIndex / MaxCount), packet.Length);
                }
                catch(Exception e)
                {
                    throw(e);
                }
                IndexCount++;
                //Runtime.Printf(GetHashCode() + "   indexStart: " + IndexStart + "   IndexCount " + IndexCount + "    " + packet.ByteIndex);
                Length = Length + packet.Length;
                if(IndexCount == MaxCount)
                {
                    var data = new SSTransReceiveBlockFullData() { TransInfo = transportInfo, Block = this };
                    EventBus.instance.Trigger(data); //把字节块存入文件
                    return 1;
                }
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }
}
